<script setup>
import { emailValid } from '@/utils/validator';
import { ElMessage} from 'element-plus';
import {  ref } from 'vue';
// 表单数据
const emailForm = ref({
    srcAddress: '2412119095@qq.com',
    emailUserName: 'admin',
    emailPassword: 'admin2024',
    attachmentStorageServerId: 'admin2024',
    attachmentStorageServerPort: '333',
    serverAccount: 'admin2024',
    serverPassword: 'admin2024',
    emailTitleFormat: 'admin2024',
    emailContent: 'admin2024Test',
    attachmentArchiveFolder: '/admin2024/test',
    imageData:''
})

const originalData = ref({})
// 表单组件实例
const formRef = ref(null)
// 弹窗可见
const dialogVisible = ref(false)
// 签名组件
const esign = ref(null)
const status = ref(1) // 当前状态? 1 -> 查看  0 -> 编辑

//签名清空
const signReset = () => {
  esign.value.reset()
}
// 生成签名
const signGenerate = () => {
  esign.value.generate().then(res => {
    emailForm.value.imageData = res
    dialogVisible.value = false
  }).catch(() => {
    ElMessage.warning('请进行签名后再操作')
  })
}
// 点击编辑
const handleClickEdit = () => {
  status.value = 0
  setTimeout(() => {
    formRef.value.clearValidate()
  })
  originalData.value = {...emailForm}
}
// 点击取消
const handleCancel = () => {
    emailForm.value = {...originalData.value}
  status.value = 1
  setTimeout(() => {
    formRef.value.clearValidate()
  })
}
// 表单校验方法
const validateField = ref({
  srcAddressValidator: (rule, value, callback) => {
    if (!emailValid(value) || value.length > 50) {
       callback(new Error('邮件格式错误'))
    }
    callback()
  },
  portValidator: (rule, value, callback) => {
    const portPattern = /^[1-9][0-9]{0,4}$/; // 匹配1到65535之间的端口号
    const port = Number(value);
    if (!portPattern.test(value) || port < 1 || port > 65535) {
      callback(new Error('请输入有效的端口号（1-65535）'));
    } else {
      callback();
    }
  },
   passwordValidator: (rule, value, callback) => {
    if (value && !/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/.test(value)) {
      callback(new Error('密码必须至少包含一个字母和一个数字，且长度不小于8个字符'));
    } else {
      callback();
    }
  },
  trimValidator: (rule, value, callback) => {

    if (value.trim().length < 5) {
      callback("长度不足")
    }
    callback()
  },
  attachmentArchiveFolderValidator: (rule, value, callback) => {
    const folderFormatRegex = /^\/([^/]+\/)*[^/]+$/;
    if (!folderFormatRegex.test(value)) {
      callback(new Error('附件存储文件夹格式错误(必须为文件夹格式)'))
    } else {
      callback()
    }
  }
})
// 表单校验
const formRules = ref({
    srcAddress: [
      { required: true, message: '请输入邮件发送地址',trigger:'blur' },
      { validator: validateField.value.srcAddressValidator,trigger:'blur'}
    ],
    emailUserName: [
      { required: true, message: '请输入用户名',trigger:'blur' },
      { min:4,max:50,message:'用户名长度在4~50',trigger:'blur'}
    ],
    emailPassword: [
      { required: true, message: '请输入密码',trigger:'blur' },
      { validator:validateField.value.passwordValidator,trigger:'blur'}
    ],
    attachmentStorageServerId: [
      { required: true, message: '请输入附件存储服务器ID',trigger:'blur' },
      { min:8,max:50,message:'存储服务器ID长度在8~50',trigger:'blur'}
    ],
    attachmentStorageServerPort: [
      { required: true, message: '请输入附件存储服务器端口',trigger:'blur' },
      { validator:validateField.value.portValidator,trigger:'blur'}
    ],
    serverAccount: [
      { required: true, message: '请输入服务账号', trigger: 'blur' },
      { min: 4, max: 50, message: '服务账号长度在4~50', trigger: 'blur' }
    ],
    serverPassword: [
      { required: true, message: '请输入服务密码', trigger: 'blur' },
      { validator: validateField.value.passwordValidator, trigger: 'blur' }
    ],
    emailTitleFormat: [
      { required: true, message: '请输入邮件标题格式', trigger: 'blur' },
      { min: 4, max: 50, message: '邮件标题格式在4~50', trigger: 'blur' },
      { validator:validateField.value.trimValidator,trigger:'blur'}

    ],
    emailContent: [
      { required: true, message: '请输入邮件内容', trigger: 'blur' },
      { min: 10, max: 225, message: '邮件内容长度在10~500', trigger: 'blur' },
      { validator:validateField.value.trimValidator,trigger:'blur'}

    ],
    attachmentArchiveFolder: [
      { required: true, message: '请输入附件存档文件夹路径', trigger: 'blur' },
      { min: 2, max: 50, message: '附件存档文件夹长度在4~50', trigger: 'blur' },
      { validator:validateField.value.attachmentArchiveFolderValidator,trigger:'blur'}

    ],
})


//点击保存
const handleSave = () => {

  formRef.value.validate(async (valid) => {
    if (!valid) {
      return ElMessage.error('请填写正确的信息')
      }
      status.value = 1
      console.log(emailForm.value.imageData);
      
  })
}
const handleClickUpload = () => {
  dialogVisible.value = true
}
</script>

<template>
    <div class="email-container">
      <!-- 画布弹窗 -->
       <el-dialog title="请输入电子签名" v-model="dialogVisible" width="40%">
        <div class="cav-container">
          <vue-esign ref="esign" :width="400" :height="400" />
          <el-button type="warning" size="default" @click="signReset">清空</el-button>
          <el-button type="primary" size="default" @click="signGenerate">确定</el-button>
        </div>
       </el-dialog>
      <div class="nav">首页/基础信息管理/邮件管理</div>
      <div class="title">
        <h3>邮件服务设置</h3>
        <div v-if="status === 1">
          <el-button size="default" @click="handleClickEdit()">编辑</el-button>
        </div>
        <div v-else>
          <el-button size="default" @click="handleCancel">取消</el-button>
          <el-button size="default" @click="handleSave">保存</el-button>
        </div>
      </div>
      <div class="form">
        <el-form ref="formRef" :model="emailForm" style="width: 100%;"  :rules="status === 1 ? null : formRules" :disabled="status === 1">
          <el-form-item label="邮件发送地址"  style="width: 40%;" prop="srcAddress">
            <el-input v-model.trim="emailForm.srcAddress" size="default" placeholder="请输入邮件发送地址"></el-input>
          </el-form-item>
          <el-form-item label="用户名" style="width: 25%;" prop="emailUserName">
            <el-input v-model.trim="emailForm.emailUserName" size="default"  placeholder="请输入用户名" ></el-input>
          </el-form-item>
          <el-form-item label="密码" style="width: 25%;" prop="emailPassword">
            <el-input v-model.trim="emailForm.emailPassword" size="default"
            placeholder="请输入密码" type="password" show-password></el-input>
          </el-form-item>
          <el-form-item label="附件存储服务器ID" style="width: 22%;" prop="attachmentStorageServerId">
            <el-input v-model.trim="emailForm.attachmentStorageServerId" size="default"  placeholder="请输入附件存储服务器ID" ></el-input>
          </el-form-item>
          <el-form-item label="附件存储服务器端口" style="width: 22%;" prop="attachmentStorageServerPort">
            <el-input v-model.trim="emailForm.attachmentStorageServerPort" size="default"  placeholder="请输入附件存储服务器端口" ></el-input>
          </el-form-item>
          <el-form-item label="附件存储服务器账号" style="width: 22%;" prop="serverAccount">
            <el-input v-model.trim="emailForm.serverAccount" size="default"  placeholder="请输入附件存储服务器账号" ></el-input>
          </el-form-item>
          <el-form-item label="附件存储服务器密码" style="width: 22%;" prop="serverPassword">
            <el-input v-model.trim="emailForm.serverPassword" size="default"  placeholder="请输入附件存储服务器密码"
            type="password" show-password></el-input>
          </el-form-item>
          <el-form-item label="邮件标题格式" style="width: 100%;" prop="emailTitleFormat">
            <el-input v-model="emailForm.emailTitleFormat" size="default"  placeholder="请输入邮件标题格式" ></el-input>
          </el-form-item>
          <el-form-item label="邮件内容" style="width: 100%;" prop="emailContent">
            <el-input v-model="emailForm.emailContent" size="default"
            placeholder="请输入邮件内容" type="textarea" :rows="5" maxlength="225" show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="附件归档文件夹" style="width: 100%;" prop="attachmentArchiveFolder">
            <el-input v-model.trim="emailForm.attachmentArchiveFolder" size="default"  placeholder="请输入附件归档文件夹" ></el-input>
          </el-form-item>
          <el-form-item label="附件电子签名" class="signatureImgContainer">
              <div>
                <img :src="emailForm.imageData" alt="" class="signatureImg"  v-if="emailForm.imageData"
                @click="handleClickUpload()">
                <el-button
                v-else @click="handleClickUpload()">点击上传签名</el-button>
              </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
</template>

<style scoped lang="less">
.email-container {
  background-color: #fff;
  padding: 20px 150px 20px 20px;
  .nav {
    color: #909a99;
    font-size: 14px;
  }
  .title {
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
    h3{
      font-weight: normal;
    }
    .el-button {
      border: none;
    }
  }
  .form {
    width: 65%;
    margin: 20px auto;
    .el-form {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
    }
    .el-form-item  {
      display: block;

    }
  }
}

::v-deep  .el-form-item__label {
    font-size: 13px;
    color: black;
  }

::v-deep .el-input__count {
  bottom: -15px !important;
}

.cav-container {
  margin: 0 auto;
  canvas {
    margin: 0 auto;
    border: 1px dotted black;
  }
}
.signatureImg {
  width: 150px;
  height: 150px;
  border: 2px dotted #dddddd;
  margin-top: 10px;
  cursor: pointer;
}

.signatureImgContainer {
  .el-button {
    width: 150px; height: 150px; border: 2px dotted #dddddd; background-color: #fafafa; margin-top: 10px;
    font-size: 17px;
  }
}
</style>
